package at.jku.pervasive;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Position
{

	private final static String regex = "^([0-9]+) ([0-9]+) (-?[0-9]+(\\.[0-9]+)?) (-?[0-9]+(\\.[0-9]+)?) (-?[0-9]+(\\.[0-9]+)?)( (true|false))?$";
	private static final Pattern positionPattern = Pattern.compile(regex);

	private Date date;
	private DecimalFormat df = new DecimalFormat("#0.0#");
	private String id;
	private double x, y, z;

	public Position()
	{
		super();
		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
		dfs.setDecimalSeparator('.');
		df.setDecimalFormatSymbols(dfs);
	}

	public Position(String id, double x, double y, double z, Date date)
	{
		this();
		this.id = id;
		this.x = x;
		this.y = y;
		this.z = z;
		this.date = date;
	}

	public Position(String posString)
	{
		this();

		Matcher matcher = positionPattern.matcher(posString);
		if (!matcher.matches())
			throw new IllegalArgumentException();

		id = matcher.group(1);

		long timestamp = Long.parseLong(matcher.group(2));
		this.date = new Date(timestamp);

		x = Double.parseDouble(matcher.group(3));
		y = Double.parseDouble(matcher.group(5));
		z = Double.parseDouble(matcher.group(7));
	}

	public Date getDate()
	{
		return date;
	}

	/**
	 * @return Returns the df.
	 */
	public DecimalFormat getDf()
	{
		return df;
	}

	/**
	 * @return Returns the id.
	 */
	public String getId()
	{
		return id;
	}

	/**
	 * @return Returns the x.
	 */
	public double getX()
	{
		return x;
	}

	/**
	 * @return Returns the y.
	 */
	public double getY()
	{
		return y;
	}

	/**
	 * @return Returns the z.
	 */
	public double getZ()
	{
		return z;
	}

	public void setDate(Date date)
	{
		this.date = date;
	}

	/**
	 * @param id The id to set.
	 */
	public void setId(String id)
	{
		this.id = id;
	}

	/**
	 * @param x The x to set.
	 */
	public void setX(double x)
	{
		this.x = x;
	}

	/**
	 * @param y The y to set.
	 */
	public void setY(double y)
	{
		this.y = y;
	}

	/**
	 * @param z The z to set.
	 */
	public void setZ(double z)
	{
		this.z = z;
	}

	@Override
	public String toString()
	{
		StringBuilder stringBuilder = new StringBuilder();

		stringBuilder.append(this.id).append(" ");
		stringBuilder.append(this.date.getTime()).append(" ");

		stringBuilder.append(df.format(this.x)).append(" ");
		stringBuilder.append(df.format(this.y)).append(" ");
		stringBuilder.append(df.format(this.z));

		return stringBuilder.toString();
	}
}
